package cn.zkdcloud.framework.servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.zkdcloud.framework.handler.RequestServletHandler;
import cn.zkdcloud.framework.render.Render;
import cn.zkdcloud.framework.handler.Handler;
import cn.zkdcloud.framework.handler.StaticResourcesHandler;


public class IndexServlet extends HttpServlet{
	
	private static List<Handler> handlers = new ArrayList<Handler>();

	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		handlers.add(new StaticResourcesHandler(getServletContext()));
		handlers.add(new RequestServletHandler());
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		Iterator<Handler> it = handlers.iterator();
		
		HttpContext httpContext = new HttpContext(req,resp);
		
		
		it.next().handler(httpContext,it);
		
	    Render render = httpContext.getRender();
	    if(render != null){
	    	render.doRender(httpContext);
	    }
	}
	
}
